import React, { useState, useEffect } from 'react'
import watermark from 'watermarkjs'
import icon from '@assets/addr.png'

const watermarkImage = (src) => {
    return new Promise((resolve, reject) => {
        const img = new Image()
        img.crossOrigin = 'Anonymous' // 设置跨域
        img.onload = () => resolve(img)
        img.onerror = reject
        img.src = src
    })
}

const WatermarkImage = ({ src, text1, text2, text3 }) => {
    const [watermarkedSrc, setWatermarkedSrc] = useState('')

    useEffect(() => {
        if (src) {
            watermarkImage(src).then((url) => {
                const iconPromise = watermarkImage(icon) // 加载图标
                iconPromise.then((icon) => {
                    // 创建带水印的图片
                    watermark([url])
                        .image((img) => customTextMark(img, icon))
                        .then((img) => {
                            setWatermarkedSrc(img.src)
                        })
                })
            })
        }
    }, [src, text1, text2, text3, icon])

    const customTextMark = (img, icon) => {
        const ctx = img.getContext('2d')
        const width = img.width
        const height = img.height

        // 绘制文本
        ctx.font = '150px 黑体'
        ctx.fillStyle = 'white'
        ctx.fillText(text1, (width - ctx.measureText(text1).width) / 2, height - 160)
        ctx.font = '35px 黑体'
        ctx.fillText(text2, (width - ctx.measureText(text2).width * 2) / 2 - 40, height - 70)
        ctx.fillText(text3, width / 2 + 40, height - 70)
        // 绘制图标
        ctx.drawImage(icon, width / 2 - 10, height - 110, 50, 50) // 调整图标位置和大小

        return img
    }

    return <img style={{ width: '100%' }} src={watermarkedSrc} alt="Watermarked" />
}

export default WatermarkImage
